import pymongo
import globalConfig

client = pymongo.MongoClient(host=globalConfig.mongo_ip, port=27017)
if globalConfig.db == "spark":
    db = client['spark_labeldata']
else:
    db = client['labeldata']


def insert_a_label(label_json):
    collection = db['label']
    result = collection.insert(label_json)
    print(result)
    return result


def get_labels_by_name(label_name):
    result = []
    print(label_name)
    collection = db['label']
    for cur in collection.find({'name': {'$regex': label_name}}):
        del cur['_id']
        result.append(cur)
    return {'results': result}


def get_labels_by_topic(topic_name):
    result = []
    print(topic_name)
    collection = db['label']
    for cur in collection.find({'topic': {'$regex': topic_name}}):
        del cur['_id']
        result.append(cur)
    return {'results': result}


def get_labels_by_ids(ids):
    result = []
    collection = db['label']
    for cur in collection.find({"id": {"$in": ids}}):
        del cur['_id']
        result.append(cur)
    return {'results': result}


def del_a_label(label_id):
    collection = db['label']
    result = collection.delete_one({"id": label_id})
    if result is None:
        return "fail"
    return "success"


def get_rules_by_topic(topic_name):
    result = []
    print(topic_name)
    collection = db['rule']
    for cur in collection.find({'topic': {'$regex': topic_name}}):
        del cur['_id']
        result.append(cur)
    return {'results': result}


def get_rules_by_ids(ids):
    result = []
    collection = db['rule']
    for cur in collection.find({"id": {"$in": ids}}):
        del cur['_id']
        result.append(cur)
    return {'results': result}


def insert_a_rule(rule_json):
    collection = db['rule']
    result = collection.insert(rule_json)
    print(result)
    return result


def del_a_rule(rule_id):
    collection = db['rule']
    result = collection.delete_one({"id": rule_id})
    if result is None:
        return "fail"
    return "success"


def get_topic_list():
    collection = db["label"]
    results = collection.distinct("topic")
    return results
